import React, {
  useEffect,
  forwardRef,
  useImperativeHandle,
  useState,
} from 'react';
import { Button, Modal, Input } from 'antd';
// import * as echarts from 'echarts/lib/echarts.js'
import * as echarts from 'echarts';
// import ReactEcharts from 'echarts-for-react';
// import 'echarts/lib/chart/line'
import styles from './echart.less';
import _, { range } from 'lodash';
import $ from 'jquery';

let indexChartTest = 0;
let scrolledPixels = 0;
var style_ul =
  'padding:0px;margin:0px;border: 1px solid #ccc;background-color: #fff;position: absolute;left: 0px;top: 0px;z-index: 2;display: none;';
var style_li =
  'list-style:none;padding: 5px; cursor: pointer; padding: 5px 20px;margin:0px;';
var style_li_hover = style_li + 'background-color: #00A0E9; color: #fff;';

//  右键菜单容器
// appendTo()在被选择元素的结尾插入HTML元素；jQuery
var menubox = $(
  "<div class='echartboxMenu' style='" +
    style_ul +
    "'><div style='text-align:center;background:#fff'></div><ul style='margin:0px;padding:0px;'></ul></div>",
).appendTo($(document.body));

const LineEcharts = forwardRef((props, ref) => {
  const { onSelectChart } = props;
  const [selectValue, setSelectValue] = useState([]);
  const [range, setRange] = useState([]);
  const [highLight, setHighLight] = useState([]);
  const [xStartValue, setXStartValue] = useState(0);
  const [xEndValue, setXEndValue] = useState(0);
  const [textOne, setTextOne] = useState('');
  const [textTwo, setTextTwo] = useState('');
  const [textThree, setTextThree] = useState('');
  const [xSet, setXSet] = useState(0);
  const [indexChart, setIndexChart] = useState(0);
  const [notesModalOne, setNotesModalOne] = useState('');
  const [notesModalTwo, setNotesModalTwo] = useState('');
  const [notesModalThree, setNotesModalThree] = useState('');

  const [isModalOpenOne, setIsModalOpenOne] = useState(false);
  const [isModalOpenTwo, setIsModalOpenTwo] = useState(false);
  const [isModalOpenThree, setIsModalOpenThree] = useState(false);

  // const [scrolledPixels,setScrolledPixels] =useState(0);
  // useImperativeHandle(ref, () => ({ onClick }));
  // const name = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
  var tooltipVisible = false; // 标识 tooltip 的显示状态
  // let xData = [1, 2, 3, 4, 5, 6, 7]
  let Xparams = null;
  let optionOne = {
    xAxis: {
      type: 'category',
      // data: [1, 2, 3, 4, 5, 6, 7],
    },
    yAxis: {
      type: 'value',
    },
    // 提示框
    // tooltip: {
    //   trigger: 'axis',
    // },
    // 工具栏
    toolbox: {
      show: true,
      feature: {
        dataZoom: {
          // 数据缩放视图
          yAxisIndex: false,
        },
        // 框选区域
        brush: {
          show: true,
          title: {
            lineX: '框选计算',
            clear: '关闭框选',
          },
        },
        // 保存图片
        // saveAsImage: { show: true }
      },
      // top: 0,
      // right: 15,
      // itemSize: 20 //工具栏 icon 的大小
    },
    brush: {
      xAxisIndex: 0,
      brushLink: 'all',
      brushMode: 'single',
      outOfBrush: {
        colorAlpha: 0.1,
      },
      toolbox: ['lineX', 'clear'],
      brushStyle: {
        borderWidth: 1,
        color: 'rgba(120,140,180,0.2)',
        borderColor: 'rgba(120,140,180,0.8)',
      },
    },
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 100,
      },
      {
        show: true,
        type: 'slider',
        top: '85%',
        start: 0,
        end: 100,
      },
    ],
    series: [
      {
        data: [10, 20, 30, 40, 50, 60, 70, 500],
        type: 'line',
        markArea: {
          data: [
            [
              {
                name: textOne,
                x: xStartValue,
                itemStyle: {
                  color: 'rgba(221, 21, 21, 1)',
                },
              },
              {
                x: xEndValue,
              },
            ],
            // [
            //   {
            //     name: "text1",
            //     x: 300,
            //     itemStyle: {
            //       color: 'rgba(221, 21, 21, 1)'
            //     }
            //   },
            //   {
            //     x: 301
            //   }
            // ]
          ],
          silent: false,
        },
      },
    ],
  };

  let optionTwo = {
    xAxis: {
      type: 'category',
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
    },
    yAxis: {
      type: 'value',
    },
    tooltip: {
      trigger: 'axis',
    },
    toolbox: {
      feature: {
        dataZoom: {
          yAxisIndex: false,
        },
        brush: {
          type: ['lineX', 'clear'],
        },
      },
    },
    brush: {
      xAxisIndex: 'all',
      brushLink: 'all',
      brushMode: 'single',
      outOfBrush: {
        colorAlpha: 0.1,
      },
    },
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 100,
      },
      {
        show: true,
        type: 'slider',
        top: '85%',
        start: 0,
        end: 100,
      },
    ],
    series: [
      {
        data: [150, 230, 224, 218, 135, 147, 260, 1000],
        type: 'line',
        markArea: {
          data: [
            [
              {
                name: textTwo,
                x: xStartValue,
                itemStyle: {
                  color: 'rgba(221, 21, 21, 1)',
                },
              },
              {
                x: xEndValue,
              },
            ],
          ],
          silent: false,
        },
      },
    ],
  };

  let optionThree = {
    xAxis: {
      type: 'category',
      data: [1, 2, 3, 4, 5, 6, 7],
    },
    yAxis: {
      type: 'value',
    },
    tooltip: {
      trigger: 'axis',
    },
    toolbox: {
      feature: {
        dataZoom: {
          yAxisIndex: false,
        },
        brush: {
          type: ['lineX', 'clear'],
        },
      },
    },
    brush: {
      xAxisIndex: 'all',
      brushLink: 'all',
      brushMode: 'single',
      outOfBrush: {
        colorAlpha: 0.1,
      },
    },
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 100,
      },
      {
        show: true,
        type: 'slider',
        top: '85%',
        start: 0,
        end: 100,
      },
    ],
    series: [
      {
        data: [150, 230, 224, 218, 135, 147, 260],
        type: 'line',
        markArea: {
          data: [
            [
              {
                name: textThree,
                x: xStartValue,
                itemStyle: {
                  color: 'rgba(221, 21, 21, 1)',
                },
              },
              {
                x: xEndValue,
              },
            ],
          ],
          silent: false,
        },
      },
    ],
  };

  let myChart = null;
  let myChart2 = null;
  let myChart3 = null;

  //框选绑定
  const onBrushSelected = (params) => {
    console.log('框选绑定', params);
    if (params.batch.length < 1 || params.batch[0].areas.length < 1) {
      $('#brushData').html('');
      return;
    }
    // 根据坐标获取选中区域数据
    let range = params.batch[0].areas[0].coordRange;
    // 1   5
    console.log('根据坐标获取选中区域的值', range);
    // debugger
    // range[(range.length) - 1] = range[(range.length) - 1] + 1;
    let brushed = [],
      nameData = [],
      sumData = [],
      meanData = [];
    let brushComponent = params.batch[0];
    for (var sIdx = 0; sIdx < brushComponent.selected.length; sIdx++) {
      var name = brushComponent.selected[sIdx].seriesName;
      console.log('myChart.getOption()----------------', myChart.getOption());
      // values表示当前框选区域的数据
      var values = myChart
        .getOption()
        .series[sIdx].data.slice(range[0], range[1] + 1);
      // console.log("-----------values", values);
      var timeData = optionOne.series[0].data.slice(range[0], range[1] + 1);
      console.log('-----------timeData', timeData);
      var timeRange = '';
      if (values.length < 1 || timeData.length < 1) {
        return;
      }
      if (timeData.length === 1) {
        timeRange = timeData[0];
      } else {
        timeRange = timeData[0] + '至' + timeData[timeData.length - 1];
      }
      // 求和
      var sum = SumNum(values) ? SumNum(values) : 0;
      // 求均值
      var mean = AverageNum(values) ? AverageNum(values) : 0;
      sumData.push(sum);
      meanData.push(mean);
      nameData.push(name);
      // console.log("sumData meanData nameData---------------------", sumData, meanData, nameData);
      var temp = `平均值：${mean.toFixed(0)}，总量：${sum}`;
      brushed.push(temp);
    }
    var text = brushed.join('');
    var brushInfo = timeRange + '\n' + text;
    $('#brushData').html(brushInfo);
    myChart.setOption({
      title: {
        backgroundColor: '#333',
        text: brushInfo,
        bottom: 0,
        right: '10%',
        width: 100,
        textStyle: {
          fontSize: 12,
          color: '#fff',
        },
      },
    });
    // 均值
    function AverageNum(arr) {
      // console.log("计算平均值", arr);
      let sum = eval(arr.join('+'));
      let svg = ((sum / arr.length) * 100) / 100;
      return svg;
    }
    // 求和
    function SumNum(arr) {
      // console.log("求和", arr);
      let sum = eval(arr.join('+'));
      return sum;
    }
  };

  const onClickChart = (params) => {
    var pointInPixel = [params.offsetX, params.offsetY];
    if (myChart.containPixel('grid', pointInPixel)) {
      var xIndex = myChart.convertFromPixel({ seriesIndex: 0 }, [
        params.offsetX,
        params.offsetY,
      ])[0];
      // console.log("xIndex", xIndex)
      indexChartTest = xIndex;
      setIndexChart(xIndex);
      var ds = optionOne.series[0].data[xIndex]; //myChart.getOption().series[0].data[xIndex]
      // console.log("ds", ds)

      // var optionTest = myChart.getOption();
      var xAxisIndex = 0; // 假设要获取的是第一个 x 轴的坐标
      // var seriesIndex = 0; // 假设要获取的是第一个系列的数据项
      // var seriesData = optionTest.series[seriesIndex].data;
      // var value = seriesData[5];
      // console.log("valueTest",value)
      var xPixel = myChart.convertToPixel({ xAxisIndex: xAxisIndex }, xIndex);
      // var xPixel = myChart.convertToPixel({ xAxisIndex: 5 }, ds);
      // console.log("xPixel", xPixel)
      setXSet(xPixel);
    }
    var event = params.event;
    var xSet = event.offsetX;
    var ySet = event.offsetY;
    console.log('鼠标点击位置像素坐标：', xSet, ySet);
  };

  // 双击设置标注
  const ondbClickChartOne = (params) => {
    console.log('进入双击事件1');
    myChart = echarts.init(document.getElementById('per_chart_1'));
    // console.log("indexChart",indexChart)
    console.log('indexChartTest', indexChartTest);

    var pointInPixel = [params.offsetX, params.offsetY];
    if (myChart.containPixel('grid', pointInPixel)) {
      var xIndex = myChart.convertFromPixel({ seriesIndex: 0 }, [
        params.offsetX,
        params.offsetY,
      ])[0];
      console.log('xIndex', xIndex);
      if (xIndex === indexChartTest) {
        // setText("Test11111111");
        // myChart.setOption(option);
        setNotesModalOne('');
        setIsModalOpenOne(true); //打开Modal窗口
      }
    }
  };

  const ondbClickChartTwo = (params) => {
    myChart = echarts.init(document.getElementById('per_chart_2'));
    console.log('进入双击事件2');
    // console.log("indexChart",indexChart)
    console.log('indexChartTest', indexChartTest);

    var pointInPixel = [params.offsetX, params.offsetY];
    if (myChart.containPixel('grid', pointInPixel)) {
      var xIndex = myChart.convertFromPixel({ seriesIndex: 0 }, [
        params.offsetX,
        params.offsetY,
      ])[0];
      console.log('xIndex', xIndex);
      if (xIndex === indexChartTest) {
        // setText("Test11111111");
        // myChart.setOption(option);
        setNotesModalTwo('');
        setIsModalOpenTwo(true); //打开Modal窗口
      }
    }
  };

  const ondbClickChartThree = (params) => {
    myChart = echarts.init(document.getElementById('per_chart_3'));
    console.log('进入双击事件3');
    // console.log("indexChart",indexChart)
    console.log('indexChartTest', indexChartTest);

    var pointInPixel = [params.offsetX, params.offsetY];
    if (myChart.containPixel('grid', pointInPixel)) {
      var xIndex = myChart.convertFromPixel({ seriesIndex: 0 }, [
        params.offsetX,
        params.offsetY,
      ])[0];
      console.log('xIndex', xIndex);
      if (xIndex === indexChartTest) {
        // setText("Test11111111");
        // myChart.setOption(option);
        setNotesModalThree('');
        setIsModalOpenThree(true); //打开Modal窗口
      }
    }
  };

  //第一个弹框 双击编辑轴线值
  const handleOkOne = () => {
    console.log('notesModalOne', notesModalOne);
    setTextOne(notesModalOne);
    setIsModalOpenOne(false);
  };

  const handleCancelOne = () => {
    setIsModalOpenOne(false);
  };

  const valueChangeModalOne = (value) => {
    setNotesModalOne(value.target.value);
  };

  //第二个弹框
  const handleOkTwo = () => {
    console.log('notesModalOne', notesModalTwo);
    setTextTwo(notesModalTwo);
    setIsModalOpenTwo(false);
  };

  const handleCancelTwo = () => {
    setIsModalOpenTwo(false);
  };

  const valueChangeModalTwo = (value) => {
    setNotesModalTwo(value.target.value);
  };

  //第三个弹框
  const handleOkThree = () => {
    console.log('notesModalOne', notesModalThree);
    setTextThree(notesModalThree);
    setIsModalOpenThree(false);
  };

  const handleCancelThree = () => {
    setIsModalOpenThree(false);
  };

  const valueChangeModalThree = (value) => {
    setNotesModalThree(value.target.value);
  };

  const drawCharts = () => {
    myChart = echarts.init(document.getElementById('per_chart_1'));
    myChart2 = echarts.init(document.getElementById('per_chart_2'));
    myChart3 = echarts.init(document.getElementById('per_chart_3'));

    // 设置不同的 option 对象，确保互相之间的事件绑定不会冲突
    myChart.setOption(optionOne);
    myChart2.setOption(optionTwo);
    myChart3.setOption(optionThree);

    // 在每个图表上绑定 brushSelected 事件  框选事件
    myChart.on('brushSelected', onBrushSelected);
    //在框选结束后，使用brushEnd事件拿到所框选区域的数据
    myChart.on('brushEnd', function (params) {
      console.log('框选结束后所选区域的数据', params);
      Xparams = params;
    });
    myChart2.on('brushSelected', onBrushSelected);
    myChart3.on('brushSelected', onBrushSelected);

    //图表的点击测试
    myChart.getZr().on('click', onClickChart);
    myChart2.getZr().on('click', onClickChart);
    myChart3.getZr().on('click', onClickChart);

    //图表的双击测试
    myChart.getZr().on('dblclick', ondbClickChartOne);
    myChart2.getZr().on('dblclick', ondbClickChartTwo);
    myChart3.getZr().on('dblclick', ondbClickChartThree);

    var showMenu = function (e, menus) {
      console.log('框选区域得操作', e, menus);
      // $("div", menubox).text(e.name);
      var menulistbox = $('ul', menubox).empty();
      $(menus).each(function (i, item) {
        var li = $("<li style='" + style_li + "'>" + item.name + '</li>');
        // .onClick(function() {
        //   console.log("clickOne")
        // });
        menulistbox.append(li);
      });
      menubox
        .css({
          left: e.event.x,
          top: e.event.y + scrolledPixels,
        })
        .show();
    };

    myChart.getZr().on('mousedown', function (e) {
      if (e.event.button === 2) {
        console.log('事件触发了吗？');
        showMenu(e, [
          {
            name: '删除',
            fn: function () {
              alert('触发-菜单1' + e.data);
              console.log('触发11111');
            },
            y: scrolledPixels,
          },
          {
            name: '保存',
            fn: function () {
              alert('触发-菜单2' + e.data);
            },
            y: scrolledPixels,
          },
        ]);
        $('.echartboxMenu').bind('click', function (e) {
          console.log(e);
          let selArr = Xparams.areas[0].coordRange;
          if (e.target.innerHTML === '删除') {
            console.log('执行了');
            //  let xData = optionOne.series[0].data.splice(selArr[0], (selArr[1] - selArr[0]) + 1)
            // optionOne.series[0].data = [500, 70, 60, 50, 40, 30]
            optionOne.series = [
              {
                data: [500, 70, 60, 50, 40, 30],
                type: 'line',
              },
            ];
            myChart.setOption(optionOne);
          }
          // console.log("xData---", xData, Xparams);
        });
      }
    });
    // 在mychart2图表上面进行鼠标右击时 出现操作菜单栏
    myChart2.getZr().on('mousedown', function (e) {
      // debugger;
      console.log('111111');
      console.log('e', e);
      if (e.event.button === 2) {
        //e中有当前节点信息
        showMenu(e, [
          {
            name: '菜单1',
            fn: function () {
              alert('触发-菜单1' + e.data);
              console.log('触发11111');
            },
            y: scrolledPixels,
          },
          {
            name: '菜单2',
            fn: function () {
              alert('触发-菜单2' + e.data);
            },
            y: scrolledPixels,
          },
        ]);
      }
    });
    // 在mychart3图表上面进行鼠标右击时 出现操作菜单栏
    myChart3.getZr().on('mousedown', function (e) {
      // debugger;
      console.log('111111');
      console.log('e', e);
      if (e.event.button === 2) {
        //e中有当前节点信息
        showMenu(e, [
          {
            name: '菜单1',
            fn: function () {
              console.log('点击菜单1');
            },
            y: scrolledPixels,
          },
          {
            name: '菜单2',
            fn: function () {
              alert('触发-菜单2' + e.data);
            },
            y: scrolledPixels,
          },
          {
            name: '菜单2',
            fn: function () {
              alert('触发-菜单2' + e.data);
            },
            y: scrolledPixels,
          },
        ]);
      }
    });

    myChart.getDom().oncontextmenu = menubox[0].oncontextmenu = function () {
      return false;
    };
    // 关闭右击鼠标时打开浏览器的上下文菜单
    myChart2.getDom().oncontextmenu = menubox[0].oncontextmenu = function () {
      return false;
    };

    //点击其他位置隐藏菜单
    // $(document).click(function () {
    //   menubox.hide()
    // });

    // 设置图表的 group 属性，并连接它们
    myChart.group = 'group1';
    myChart2.group = 'group1';
    myChart3.group = 'group1';

    echarts.connect('group1');
  };

  useEffect(() => {
    setXStartValue(xSet);
    let endValue = xSet + 1;
    setXEndValue(endValue);
    setTextOne('');
    setTextTwo('');
    setTextThree('');
    // console.log("xSet", xSet)
  }, [xSet]);

  //textOne
  useEffect(() => {
    console.log('textOne 改变');
    if (textOne !== '') {
      console.log('textOne', textOne);
      myChart = echarts.init(document.getElementById('per_chart_1'));
      myChart.setOption(optionOne);
    }
  }, [textOne]);

  //textTwo
  useEffect(() => {
    console.log('textTwo 改变');
    if (textTwo !== '') {
      console.log('textTwo', textTwo);
      myChart = echarts.init(document.getElementById('per_chart_2'));
      myChart.setOption(optionTwo);
    }
  }, [textTwo]);

  //textThree
  useEffect(() => {
    console.log('textThree 改变');
    if (textThree !== '') {
      console.log('textThree', textThree);
      myChart = echarts.init(document.getElementById('per_chart_3'));
      myChart.setOption(optionThree);
    }
  }, [textThree]);

  useEffect(() => {
    console.log('indexChart useEffect', indexChart);
  }, [indexChart]);

  useEffect(() => {
    myChart = echarts.init(document.getElementById('per_chart_1'));
    myChart2 = echarts.init(document.getElementById('per_chart_2'));
    myChart3 = echarts.init(document.getElementById('per_chart_3'));

    myChart.setOption(optionOne);
    myChart2.setOption(optionTwo);
    myChart3.setOption(optionThree);
  }, [xStartValue]);

  const handleScroll = () => {
    // 获取网页进度条滚动掉的像素
    const scrolledPixelsTest = window.scrollY;

    // console.log('滚动像素：', scrolledPixelsTest);
    scrolledPixels = scrolledPixelsTest;
    // setScrolledPixels(scrolledPixelsTest);
  };
  useEffect(() => {
    drawCharts();
    window.addEventListener('scroll', handleScroll);
    // window.addEventListener('mousemove', handleWindowMouseMove);
    //   myChart.dispatchAction({ type: 'brush', areas: [{
    //     brushType: 'lineX',
    //     coordRange: ['Sat', 'Sun'],
    //     xAxisIndex: 0
    //   }]
    // });
  }, []);
  useEffect(() => {
    console.log('框选像素变化时刷新页面');
    myChart = echarts.init(document.getElementById('per_chart_1'));
    myChart2 = echarts.init(document.getElementById('per_chart_2'));
    myChart3 = echarts.init(document.getElementById('per_chart_3'));

    // 设置不同的 option 对象，确保互相之间的事件绑定不会冲突
    myChart.setOption(optionOne);
    myChart2.setOption(optionTwo);
    myChart3.setOption(optionThree);
  }, [JSON.stringify(range)]);

  const handleClick = (event) => {
    console.log('handleClick 进入');
    const x = event.clientX;
    const y = event.clientY;
    console.log(x + '//' + y);
    // 在这里可以使用 x 和 y 来执行你的逻辑
    // ...
  };
  return (
    <div>
      <div
        className={styles.base_disposal}
        key="帧数"
        style={{ marginTop: '24px' }}
      >
        <div className={styles.disposal_header}>
          <div className={styles.disposal_bar}></div>
          <div className={styles.disposal_title}>帧数</div>
          <img className={styles.disposal_picture} src="" />
        </div>
        <div className={styles.disposal_dates} style={{ width: '100%' }}>
          <div
            id="per_chart_1"
            style={{
              width: '100%',
              height: 400,
            }}
            onEvents={{
              click: handleClick, // 绑定点击事件处理函数
            }}
          >
            {' '}
          </div>
        </div>
      </div>

      <div
        className={styles.base_disposal}
        key="卡顿分布"
        style={{ marginTop: '24px' }}
      >
        <div className={styles.disposal_header}>
          <div className={styles.disposal_bar}></div>
          <div className={styles.disposal_title}>帧率/卡顿分布</div>
          <img className={styles.disposal_picture} src="" />
        </div>
        <div className={styles.disposal_dates} style={{ width: '100%' }}>
          <div
            id="per_chart_2"
            style={{
              width: '100%',
              height: 400,
            }}
          >
            {' '}
          </div>
        </div>
      </div>

      <div
        className={styles.base_disposal}
        key="负载"
        style={{ marginTop: '24px' }}
      >
        <div className={styles.disposal_header}>
          <div className={styles.disposal_bar}></div>
          <div className={styles.disposal_title}>连续帧分布</div>
          <img className={styles.disposal_picture} src="" />
        </div>
        <div className={styles.disposal_dates} style={{ width: '100%' }}>
          <div
            id="per_chart_3"
            style={{
              width: '100%',
              height: 400,
            }}
          >
            {' '}
          </div>
        </div>
      </div>

      <Modal
        title="设置备注1"
        open={isModalOpenOne}
        onOk={handleOkOne}
        onCancel={handleCancelOne}
      >
        <Input
          placeholder="Basic usage"
          onChange={valueChangeModalOne}
          value={notesModalOne}
        />
      </Modal>

      <Modal
        title="设置备注2"
        open={isModalOpenTwo}
        onOk={handleOkTwo}
        onCancel={handleCancelTwo}
      >
        <Input
          placeholder="Basic usage"
          onChange={valueChangeModalTwo}
          value={notesModalTwo}
        />
      </Modal>

      <Modal
        title="设置备注3"
        open={isModalOpenThree}
        onOk={handleOkThree}
        onCancel={handleCancelThree}
      >
        <Input
          placeholder="Basic usage"
          onChange={valueChangeModalThree}
          value={notesModalThree}
        />
      </Modal>
    </div>
  );
});
export default LineEcharts;
